iT邦幫忙

2

【c#】NameValueCollection 和 Dictionary 差異??

石頭 2017-11-07 21:25:3612660 瀏覽
  • 分享至 

  • xImage
  •  

前言:

NameValueCollection v.s Dictionary

使用起來很像的東西 其實差很大...

NameValueCollection 和 Dictionary<> 比較下表

NameValueCollection Dictionary<,>
Key和Value 都是String型態 可用泛型來指定Key和Value型態
可對於未指定的Key取值 不能對於未指定的Key取值 (會報錯誤)
可對於重複鍵Add值 不可於重複鍵Add值

(一)

  1. NameValueCollection的Key和Value 只吃 string

    NameValueCollection contatier = new NameValueCollection();
    contatier.Add("key1", "key1");
    contatier.Add("key2", "key2");
    
  2. 使用Dictionary可用泛型指定Key和Value的型態

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("key1", "key1");
    dict.Add("key2", "key2");   
    

(二)

  1. Dictionary字典物件 沒有給key為dict付值 取值時會出錯

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("key1", "key1");
    dict.Add("key2", "key2");
    Console.WriteLine(dict["dict"]);
    
  2. 雖然在下面的contaier沒有給Key為dict值 但再取值時不會報錯 而是會給一個**[空字串]**

    NameValueCollection contatier = new NameValueCollection();
    contatier.Add("key1", "key1");
    contatier.Add("key2", "key2");
    Console.WriteLine(contatier["dict"]);  
    

(三)

  1. NameValueCollection可以使用重複Key來付值 如以下程式碼 重複add [Key]為key1 可正常運作

    NameValueCollection contatier = new NameValueCollection();
    contatier.Add("key1", "key1");
    contatier.Add("key2", "key2");
    contatier.Add("key1", "test1");
    
  2. 下面dict 字典物件使用如重複Key來付值會出錯 如重複add [Key]為key1 就會報錯

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("key1", "key1");
    dict.Add("key2", "key2");
    dict.Add("key1", "test1");  
    

其中第二點和第三點差別須注意


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
小魚
iT邦大師 1 級 ‧ 2017-11-08 01:20:21

可是這樣NameValueCollection如果同樣Key值要取值會取到哪個值。
如果是Dictionary因為是唯一Key值,所以一定會取到我要的值。

看更多先前的回應...收起先前的回應...
石頭 iT邦高手 1 級 ‧ 2017-11-08 07:37:32 檢舉

NameValueCollection如果同樣Key 會抓你最後add值

Dictionary因為是唯一Key值,所以一定會取到我要的值。

這句話有點怪怪的,Dictionary的key是唯一鍵,不予許重複add同樣的Key不然會出錯/images/emoticon/emoticon16.gif

攻城屍 iT邦新手 4 級 ‧ 2017-11-08 09:43:54 檢舉

NameValueCollection如果同樣Key 會抓你最後add值

若新增已存在的 Key 會將新字串以逗號區隔的方式加在原字串後方唷
且要注意 NameValueCollection 的 Key並無區分大小寫

石頭 iT邦高手 1 級 ‧ 2017-11-08 09:49:19 檢舉

/images/emoticon/emoticon12.gif哈哈 感謝^^

小魚 iT邦大師 1 級 ‧ 2017-11-08 12:15:26 檢舉

不予許重複add同樣的Key不然會出錯

這句話是沒錯啦,
如果不確定會不會重複,
可以在add之前先做判斷,
再決定要不要add.

我要留言

立即登入留言